import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:复制文件
 * Author: WJW
 * Date: 2024-08-21
 * Time: 11:03
 */
public class IODemo2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要复制的文件:");
        String srcPath = scanner.next();
        System.out.println("请输入要复制的目标文件:");
        String destPath = scanner.next();

        //合法判断
        //1）scrPath对应的文件是否存在
        File srcFile = new File(srcPath);
        if(!srcFile.isFile()){
            System.out.println("源文件路径有误！");
            return;
        }
        //2)destPath 不要求对应的文件存在，但是目录得存在
        File destFile = new File(destPath);
        if(!destFile.getParentFile().isDirectory()){
            System.out.println("目标路径有误");
            return;
        }

        //复制操作
        try(InputStream inputStream = new FileInputStream(srcFile);
            OutputStream outputStream = new FileOutputStream(destFile)){
            while(true){
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n == -1){
                    //读取文件
                    break;
                }
                //把读到的内容写到outPutStream中
                outputStream.write(buffer,0,n);

            }

        }  catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
